package net.xiaosaguo.mymall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.xiaosaguo.common.utils.PageUtils;
import net.xiaosaguo.common.utils.Query;
import net.xiaosaguo.mymall.product.dao.SkuInfoDao;
import net.xiaosaguo.mymall.product.entity.SkuImagesEntity;
import net.xiaosaguo.mymall.product.entity.SkuInfoEntity;
import net.xiaosaguo.mymall.product.entity.SpuInfoDescEntity;
import net.xiaosaguo.mymall.product.service.*;
import net.xiaosaguo.mymall.product.vo.SkuItemSaleAttrVO;
import net.xiaosaguo.mymall.product.vo.SkuItemVO;
import net.xiaosaguo.mymall.product.vo.SpuItemAttrGroupVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;


/**
 * @author x
 */
@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    SkuImagesService skuImagesService;
    @Autowired
    SpuInfoDescService spuInfoDescService;
    @Autowired
    AttrGroupService attrGroupService;
    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    ThreadPoolExecutor threadPool;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();
        // 模糊查询
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and(w -> w.eq("sku_id", key).or().like("sku_name", key));
        }
        // 品牌
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equals(brandId)) {
            queryWrapper.eq("brand_id", brandId);
        }
        // 分类
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equals(catelogId)) {
            queryWrapper.eq("catalog_id", catelogId);
        }
        // min 查询
        String min = (String) params.get("min");
        if (!StringUtils.isEmpty(min)) {
            queryWrapper.ge("price", min);
        }
        // max 查询
        String max = (String) params.get("max");
        if (!StringUtils.isEmpty(max)) {
            try {
                BigDecimal bigDecimal = new BigDecimal(max);
                if (bigDecimal.compareTo(new BigDecimal(0)) > 0) {
                    queryWrapper.le("price", max);
                }
            } catch (Exception e) {
                log.warn("输入的最大价格有误：max = " + max);
            }

        }

        IPage<SkuInfoEntity> page = this.page(new Query<SkuInfoEntity>().getPage(params), queryWrapper);
        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.save(skuInfoEntity);
    }

    @Override
    public SkuItemVO item(Long skuId) throws ExecutionException, InterruptedException {

        SkuItemVO skuItemVO = new SkuItemVO();
        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            // 1. sku 基本信息获取 pms_sku_info
            SkuInfoEntity info = this.getById(skuId);
            skuItemVO.setInfo(info);
            return info;
        }, threadPool);

        CompletableFuture<Void> saleAttrsFuture = infoFuture.thenAcceptAsync(info -> {
            // 3. 获取 spu 的销售属性组合
            List<SkuItemSaleAttrVO> saleAttrs = skuSaleAttrValueService.getSaleAttrsBySpuId(info.getSpuId());
            skuItemVO.setSaleAttrs(saleAttrs);
        }, threadPool);

        CompletableFuture<Void> spuDescFuture = infoFuture.thenAcceptAsync(info -> {
            // 4. spu 介绍
            SpuInfoDescEntity spuDesc = spuInfoDescService.getById(info.getSpuId());
            skuItemVO.setDesp(spuDesc);
        }, threadPool);

        CompletableFuture<Void> groupAttrsFuture = infoFuture.thenAcceptAsync(info -> {
            // 5. 获取规格参数组及组下的规格参数
            List<SpuItemAttrGroupVO> groupAttrs = attrGroupService.getAttrGroupWithAttrBySpuId(info.getSpuId(), info.getCatalogId());
            skuItemVO.setGroupAttrs(groupAttrs);
        }, threadPool);

        CompletableFuture<Void> imagesFuture = CompletableFuture.runAsync(() -> {
            // 2. 获取sku图片信息 pms_sku_images
            List<SkuImagesEntity> images = skuImagesService.lambdaQuery().eq(SkuImagesEntity::getSkuId, skuId).list();
            skuItemVO.setImages(images);
        }, threadPool);

        // 等待所有任务都完成
        CompletableFuture.allOf(saleAttrsFuture, spuDescFuture, groupAttrsFuture, imagesFuture).get();

        return skuItemVO;
    }

}